package com.jr.platform.generator.CodeGen;

import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jr.platform.domain.*;
import com.jr.platform.domain.Enums.ColumTypeEnum;
import com.jr.platform.service.AutoTableService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author xy
 */
@Component
@RequiredArgsConstructor
public class PreviewSql {

    private final AutoTableService autoTableService;
    public Map<String,StringBuilder> sqlmap = new HashMap<>();
    private Map<String,String> tableIds = new HashMap<>();

    /**
     * 拼装预览sql
     * @param json
     * @return
     */
    public String preview(String json) {
        CustomInterface customInterface = JSONUtil.toBean(json, CustomInterface.class);
        JSONObject data = JSONUtil.getByPath(new JSONObject(customInterface.getResult()), "data", new JSONObject());
        createTable(data,"parent","0",Optional.ofNullable((Long)data.get("id")).orElse(null));
        StringBuilder previewSql = new StringBuilder();
        //拼装所有的sql并创建表
        sqlmap.forEach((k,v)->{
            v.append("primary key(id)) engine=innoDB default charset=utf8;");

            //遍历判断是否为修改表
            if(tableIds.get(k)==null){
                //不是修改表则创建表
                previewSql.append(v+"\r\n"+"\r\n");
            }
        });
        return previewSql.toString();
    }


    /**
     * 解析result
     * @param data
     * @param tableName
     */
    public void createTable(JSONObject data , String tableName, String status, Long id){
        //判断当前表名称生成的次数
        int count = autoTableService.count(new LambdaQueryWrapper<AutoTable>().eq(AutoTable::getParamName, tableName));
        //存入数据库
        AutoTable autoTable = new AutoTable();
        autoTable.setParamName(tableName);
        autoTable.setId(id);
        autoTable.setRepetCount(StrUtil.toString(count));
        autoTable.setTableName(tableName+"_table"+StrUtil.toString(count));
        autoTable.setStatus(status);
        //第一次创建建表语句
        StringBuilder sql2 = new StringBuilder("CREATE TABLE IF NOT EXISTS  "+ autoTable.getTableName()+" ( id bigint auto_increment COMMENT '主键', parentid bigint COMMENT '父id',");
        //放入map方便后面根据key寻找
        sqlmap.put(autoTable.getTableName(),sql2);
        tableIds.put("tableName",data.get("id")!=null?data.get("id").toString():null);

        data.forEach((k,v)->{
            JSONObject entries = JSONUtil.parseObj(v);
            //类型是Object
            if(StrUtil.equals(entries.get("type").toString(),"object")){
                createTable(JSONUtil.parseObj(entries.get("info")),k.toString(),entries.get("status").toString(), Optional.ofNullable((Long)entries.get("id")).orElse(null));
            } else
                //类型是List
                if(StrUtil.equals(entries.get("type").toString(),"list")){
                    //并且类型是object
                    Optional<Object> info = Optional.ofNullable(entries.get("info"));
                    info.ifPresent(val->
                            {
                                //设置表状态
                                createTable(JSONUtil.parseObj(val),k.toString(),entries.get("status").toString(),Optional.ofNullable((Long)entries.get("id")).orElse(null));
                            }
                    );
                } else {
                    Map<String, Object> enumMap = EnumUtil.getNameFieldMap(ColumTypeEnum.class, "value");
                    sqlmap.get(autoTable.getTableName()).append(k+" "+enumMap.get(entries.get("type").toString().toUpperCase())+" comment '"+entries.get("comment").toString()+"',");
                }
        });
    }
}
